from selenium import webdriver
import time
import datetime

import smtplib  # 邮件发送动作

from email.mime.text import MIMEText  # 用于构建邮件内容

from email.header import Header  # 用于构建邮件头




# 发送邮件
def send_email():
    # 发信人
    from_user = '935043982@qq.com'
    password = 'exntghlrczqobfja'

    # 收信人
    to_user = '1067241118@qq.com'

    # 发信服务器
    smtp_server = 'smtp.qq.com'

    # 正文内容，第一个参数为内容，第二个参数为格式(plain 为纯文本)，第三个参数为编码
    msg = MIMEText('约课成功', 'plain', 'utf-8')

    # 邮件头信息
    msg['From'] = Header(from_user)
    msg['To'] = Header(to_user)
    msg['Subject'] = Header('约课信息')

    # 开启发信服务，加密传输
    server = smtplib.SMTP_SSL(smtp_server)
    server.connect(smtp_server, 465)

    # 登录发送邮箱
    server.login(from_user, password)

    # 发邮件
    server.sendmail(from_user, to_user, msg.as_string())

    # 关闭服务器
    server.quit()
    exit()


# 取消预约
def cancel(browser):
    font = browser.find_elements_by_xpath("//table[@class='dede_table']/tbody/tr/td//font")
    for item in font:
        print(item.text)
        if item.text == ' 撤销':
            item.click()
            a = browser.switch_to.alert
            a.accept()
            break


# 约课
def choose_class(minclass,maxclass):
    i = 0
    font = browser.find_elements_by_xpath("//table[@class='dede_table']/tbody/tr/td//font")
    for item in font:
        i = i + 1
        print(item.text)
        if minclass <= i <= maxclass and item.text == '预约':
            item.click()
            send_email()


browser = webdriver.Chrome()

browser.get("http://www.kucarlife.com/WebAPP/login_zjjs.php")

browser.find_element_by_class_name("zhanghao").clear()

browser.find_element_by_class_name("zhanghao").send_keys("卢杰7472")

browser.find_element_by_class_name("mima").clear()

browser.find_element_by_class_name("mima").send_keys("217472")

browser.find_element_by_class_name("denglu").click()

nowtime = datetime.datetime.now()

year = nowtime.strftime('%Y')

month = nowtime.strftime('%m')

day = nowtime.strftime('%d')
daytime = input("请输入1or2（1表示一天后，2表示两天后）")
day = int(day) + int(daytime)

day = '0' + str(day)

base_url = 'http://es.kucarlife.com:9090/servplat/webAppPage/studydate/smartdodate.php?DEPT_ID=3&STUDENT_ID=157042' \
           '&TEACHER_ID=028998 '

url = base_url + '&CDATE=' + year + '-' + month + '-' + day + '&KEMUNO=2&VM_NUM=%CF%E6GJ780%D1%A7'

browser.get(url)
minclass=input("请输入约课区间上限:")
maxclass=input("请输入约课区间下限:")
while True:
    choose_class(int(minclass),int(maxclass))
    time.sleep(2)
